#include "device/dev_manager.h"

namespace iecas_ns
{
    shared_ptr<CDevManager> CDevManager::sm_intancePtr = nullptr;

    CDevManager::CDevManager()
    {
        m_commonPtr = shared_ptr<CCommon>(CCommon::getInstance());
        m_jsonUsrPtr = shared_ptr<CJsonUsr>(CJsonUsr::getInstance());
        m_devCommonPtr = shared_ptr<CDevCommon>(CDevCommon::getInstance());
        m_devStaticPtr = shared_ptr<CDevStatic>(CDevStatic::getInstance());
        m_devHotplugPtr = shared_ptr<CDevHotplug>(CDevHotplug::getInstance());
        m_ipscanPtr = shared_ptr<CIpScan>(CIpScan::getInstance());
        m_dev_fd_stat.clear();
    }

	shared_ptr<CDevManager> CDevManager::getInstance()
	{
		if(sm_intancePtr == nullptr)
		{
			sm_intancePtr = shared_ptr<CDevManager>(new CDevManager());
		}
		return sm_intancePtr;
	}

    bool CDevManager::init(void)
    {
        m_devStaticPtr->init();
        m_devHotplugPtr->init();
        m_ipscanPtr->init();
        return true;
    }

    void CDevManager::start(void)
    {
        m_devStaticPtr->start();
        m_devHotplugPtr->start();
        m_ipscanPtr->start();
        thread tempThread(&CDevManager::loop, this);
        tempThread.detach();
    }

    void CDevManager::loop(void)
    {
        while(true)
        {
            if(!writeDeviceFile())
            {
                cout << "write device file failed" << endl;
                PLOGD << "write device file failed";
            }
            if(!writeIpNameFile())
            {
                cout << "write device file failed" << endl;
                PLOGD << "write device file failed";
            }
            sleep(3);
        }
    }

    bool CDevManager::writeDeviceFile(void)
    {
        m_dev_fd_stat.clear();

        m_commonPtr->getDevJson(m_dev_fd_stat);

        if(m_jsonUsrPtr->writeToJsonFile(DEVICES_JSON_FILE_NAME, m_dev_fd_stat))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

        bool CDevManager::writeIpNameFile(void)
    {
        m_ip_name.clear();

        m_commonPtr->getIpNameJson(m_ip_name);

        if(m_jsonUsrPtr->writeToJsonFile(IPNAME_JSON_FILE_NAME, m_ip_name))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
